'use strict';
/**
 * @fileoverview 幸运宝箱
 * @author sundbcn@gmail.com (sun debing)
 */

var mongoose = require('mongoose');
var moment = require('moment');
var _ = require('lodash');
var constantUtil = require('../util/constantUtil');
var luckyBoxMgr = require('../mgr/luckyBoxMgr');
var dataApi = require('../libs/dataApi');

///////////////////////////////////////////////////////////
/**
 * 转盘奖励item
 * @type {mongoose}
 */
var luckyBoxItemSchema = new mongoose.Schema({
    // 宝箱id
    box_id: {
        type: Number,
        default: 0
    },

    // 结束时间
    last_time: {
        type: Number,
        default: 0
    },

    // 间隔时间
    interval_time: {
        type: Number,
        default: 0
    },

    // 免费次数
    free_num: {
        type: Number,
        default: 0
    }

});

if (!luckyBoxItemSchema.options.toJSON) {
    luckyBoxItemSchema.options.toJSON = {};
}

/* jshint unused:false */
luckyBoxItemSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};

// 始始宝箱数据
var _infoBox = function () {
    var info_list = [];
    dataApi.lucky_box.each(function (lucky_box_conf, lucky_box_id) {
        var free_num = dataApi.lucky_box.findById(lucky_box_id).free_times_limit;
        info_list.push({
            box_id: lucky_box_id,
            last_time: moment().unix() + lucky_box_conf.cd_time,
            interval_time: lucky_box_conf.cd_time,
            free_num: free_num
        });
    });
    return info_list;
};

/**
 * 幸运宝箱
 */
var LuckyBoxSchema = new mongoose.Schema({
    // 角色id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 单抽次数  -- 10次必出紫
    receive_num: {
        type: Number,
        default: 0
    },

    // 列表
    lucky_box_queue_list: {
        type: [luckyBoxItemSchema],
        default: _infoBox
    }
});

LuckyBoxSchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 单抽次数
 * @return {[type]} [description]
 */
LuckyBoxSchema.methods.addOnlyReceiveNum = function (num) {
    if (this.receive_num < num - 1) {
        this.receive_num++;
        return false;
    } else {
        this.receive_num = 0;
        return true;
    }
};

/**
 * 扣除免费次数
 * @return {[type]} [description]
 */
LuckyBoxSchema.methods.subFreeNum = function (box_id) {
    var isVaild = false;
    _.some(this.getLuckyBoxQueueList(), function (item) {
        if (item.box_id == box_id) {
            if (item.free_num >= 1) {
                item.free_num--;
                isVaild = true;
                return true;
            }
        }
    });
    return isVaild;
};

/**
 * 每天重置免费次数
 * @return {[type]} [description]
 */
LuckyBoxSchema.methods.refresh = function () {
    _.some(this.getLuckyBoxQueueList(), function (item) {
        var free_num = dataApi.lucky_box.findById(item.box_id).free_times_limit;
        item.free_num = free_num;
    });
};

/**
 * 免费时间内重置为当前时间
 * @return {[type]} [description]
 */
LuckyBoxSchema.methods.isFree = function (box_id) {
    var is_valid = false;
    var now_time = moment().unix();
    var conf = dataApi.lucky_box.findById(box_id);
    _.some(this.getLuckyBoxQueueList(), function (value) {
        if (value.box_id == box_id) {
            if (now_time >= value.last_time) {
                value.last_time = now_time + conf.cd_time;
                is_valid = true;
                return true;
            }
        }
    });
    return is_valid;
};

/**
 * 获取列表
 * @return {[type]} [description]
 */
LuckyBoxSchema.methods.getLuckyBoxQueueList = function () {
    return this.lucky_box_queue_list;
};

/**
 * 获取修改
 * @return {[type]} [description]
 */
LuckyBoxSchema.methods.getLastChange = function () {
    return this.toJSON();
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
LuckyBoxSchema.methods.push = function () {
    this.pushModify();
};

LuckyBoxSchema.methods.pushModify = function () {
    luckyBoxMgr.sendLuckBoxChanged(
        this.role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send luckyBox message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

if (!LuckyBoxSchema.options.toJSON) {
    LuckyBoxSchema.options.toJSON = {};
}
/* jshint unused:false */
LuckyBoxSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};

mongoose.model('LuckyBox', LuckyBoxSchema);
